package com.project.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.UserBean;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService implements IUserService {

    @Autowired
    private IUserMapper userMapper;
    @Override
    public List<UserBean> findAllUsers() {
        return userMapper.selectList(null);
    }

    @Override
    public boolean addUser(UserBean user) {
        QueryWrapper<UserBean> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("u_username",user.getUserName());
        UserBean existingUser = userMapper.selectOne(queryWrapper);
        if (existingUser != null) {
            return false;
        }
        userMapper.insert(user);
        return true;
    }

    @Override
    public void deleteUser(Integer userId) {
            userMapper.deleteById(userId);
    }

    @Override
    public UserBean findUserById(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public void updateUserGrade(Integer userId, String newGrade) {
        UserBean userBean = userMapper.selectById(userId);
        userBean.setGrade(newGrade);
        userMapper.updateById(userBean);
    }

    @Override
    public void updatePwd(Integer id, String newPwd) {
           UserBean userBean = userMapper.selectById(id);
            userBean.setPwd(newPwd);
            userMapper.updateById(userBean);
    }

    @Override
    public UserBean login(String userName, String password) {
        // 根据用户名查询用户信息
        UserBean user = userMapper.selectOne(
                new QueryWrapper<UserBean>().eq("u_username", userName));
        if (user == null) {
            // 如果用户不存在，返回 null
            return null;
        }
        // 对比密码是否正确
        if (!user.getPwd().equals(password)) {
            // 如果密码不正确，返回 null
            System.out.println("+++++++++++++++++++"+user.getPwd());
            System.out.println(password);
            return null;
        }
        // 登录成功，返回用户对象
        return user;
    }
}
